package com.briup.estore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.estore.dao.RecommendShopDao;
import com.briup.estore.dao.UserDao;
import com.briup.estore.entity.RecommendShopEntity;
import com.briup.estore.entity.ShopEntity;
import com.briup.estore.entity.UserEntity;
import com.briup.estore.service.UserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import sun.security.provider.MD5;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author adam
 * @date 2023/3/31
 */
@Slf4j
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RecommendShopDao recommendShopDao;
    @Override
    public void register(UserEntity userEntity) {
        //验证用户名是否存在
        Long count = userDao.selectCount(new QueryWrapper<UserEntity>().eq("login_name", userEntity.getLoginName()));
        if (count > 0) {
            throw new RuntimeException("登录名称已经被注册请更换登录名重试！");
        }
        userDao.insert(userEntity);
    }

    @Override
    //判断用户是否存在
    //账户是否可用
    //校验密码是否正确
    public UserEntity login(String loginName, String password) {
        //通过用户名去查询用户
        UserEntity user = userDao.selectOne(new QueryWrapper<UserEntity>().eq("login_name", loginName));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        } else {
            if (user.isLock()) {
                throw new RuntimeException("账号不可用请联系管理员");
            } else {
                String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
                log.debug("传入字符串的明文:{}",password);
                log.debug("传入字符串的暗文:{}",passwordMd5);
                log.debug("数据库中的暗文:{}",user.getPasswordMd5());
                //校验密码
                if (passwordMd5.equals(user.getPasswordMd5())) {
                   return  user;
                }else{
                    throw  new  RuntimeException("用户名密码错误");
                }

            }

        }

    }


}
